package com.miracle.moa.manager.controller;


import com.miracle.common.Result;
import com.miracle.common.StatusCode;
import com.miracle.moa.manager.entity.Dept;
import com.miracle.moa.manager.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 部门表 前端控制器
 * </p>
 *
 * @author miracle
 * @since 2021-03-22
 */
@RestController
@RequestMapping("/manager/dept")
public class DeptController {

    @Autowired
    private IDeptService deptService;

    /**
     * 查询部门树
     *
     * @return Result<List<Dept>>
     */
    @GetMapping("/listDeptTree")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result<List<Dept>> listDeptTree(@RequestParam(required = false, name = "deptName") String deptName) {
        return deptService.listDeptTree(deptName);
    }

    /**
     * 保存部门信息
     *
     * @param dept 部门信息
     * @return Result<Dept>
     */
    @PostMapping("/save")
    public Result<Dept> save(@Validated @RequestBody Dept dept) {
        LocalDateTime now = LocalDateTime.now();
        dept.setCreateTime(now);
        dept.setUpdateTime(now);
        deptService.save(dept);
        return new Result<>(StatusCode.OK, "保存成功", dept);
    }

    /**
     * 更新部门信息
     *
     * @param dept 部门信息
     * @return Result<Dept>
     */
    @PostMapping("/edit")
    public Result<Dept> edit(@Validated @RequestBody Dept dept) {
        if (dept.getId().equals(dept.getParentId())) {
            return new Result<>(StatusCode.ERROR, "请勿选择自己作为父级！", dept);
        }
        LocalDateTime now = LocalDateTime.now();
        dept.setUpdateTime(now);
        deptService.updateById(dept);
        return new Result<>(StatusCode.OK, "更新成功", dept);
    }

    /**
     * 根据id删除部门
     *
     * @param id 部门id
     * @return Result
     */
    @DeleteMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable int id) {
        deptService.removeById(id);
        return new Result<>(StatusCode.OK, "删除成功", null);
    }

}
